/**
 * $Id: PaginationTag.java 19 2011-06-11 04:06:06Z feigme $
 */
package com.iary.interfaces.taglib;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iary.infrastructure.orm.Page;

public class PaginationTag extends TagSupport {

	private static final long serialVersionUID = 2105673440806872545L;
	
	private static final Logger log = LoggerFactory
			.getLogger(PaginationTag.class);

	private String url;

	private String param;

	@SuppressWarnings("unchecked")
	@Override
	public int doStartTag() throws JspException {
		Page page = (Page) pageContext.getRequest().getAttribute("page");
		if (page != null) {
			Locale locale = Locale.getDefault();
			ResourceBundle bundle = ResourceBundle.getBundle(
					"i18n/globalMessages", locale);

			StringBuffer str = new StringBuffer();
			str.append("<table><tr><td>");

			if (page.getTotalCount() > 0) {
				str
						.append(MessageFormat.format(bundle
								.getString("common.total.count"), page
								.getTotalCount()));
				str.append("&nbsp;");
			}
			if (page.getTotalPages() > 0) {
				str.append(MessageFormat.format(bundle
						.getString("common.total.page"), page.getTotalPages()));
				str.append("&nbsp;");
			}

			if (page.isHasPre()) {
				str.append(buildUrl(page.getPrePage(), bundle
						.getString("common.prev")));
			}

			if (page.getTotalPages() > 1) {
				for (int i = 1; i <= page.getTotalPages(); i++) {
					str.append("&nbsp;");
					if (page.getPageNo() != i) {
						str.append(buildUrl(i, String.valueOf(i)));
					} else {
						str.append(i);
					}
				}
			}

			if (page.isHasNext()) {
				str.append("&nbsp;");
				str.append(buildUrl(page.getNextPage(), bundle
						.getString("common.next")));
			}

			str.append("</td></tr></table>");

			try {
				pageContext.getOut().write(str.toString());
			} catch (IOException e) {
				log.warn(e.getMessage());
			}
		}

		return SKIP_BODY;
	}

	private String buildUrl(int pageNo, String txt) {
		StringBuffer str = new StringBuffer();
		str.append("<a href=\"");
		str.append(url).append("?pageNo=").append(pageNo);
		if (getParam() != null && !"".equals(getParam())) {
			str.append("&").append(getParam());
		}
		str.append("\">");
		str.append(txt);
		str.append("</a>");
		return str.toString();
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

}
